# -*- coding:utf-8 -*-
from tokenize import String
from datetime import datetime,timedelta
import os,shutil
import re
import random
import json
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from STool.StockTT import *

class StockTool:
    def __init__(self):
        pass
    

    


    @classmethod
    def getlastseason(self,today):
        # today = datetime.strptime(today, '%Y-%m-%d')
        quarter = (today.month - 1) / 3 + 1
        if quarter == 1:
            return datetime(today.year - 1, 12, 31).strftime('%Y-%m-%d')
        elif quarter == 2:
            return datetime(today.year, 3, 31).strftime('%Y-%m-%d')
        elif quarter == 3:
            return datetime(today.year, 6, 30).strftime('%Y-%m-%d')
        else:
            return datetime(today.year, 9, 30).strftime('%Y-%m-%d')

    @classmethod
    def getTodayString(self):

        today_String = datetime.now().strftime('%Y-%m-%d')
        return today_String

    @classmethod
    def getRPSIntervalDateString(self,RPS):
        lastMonth = datetime.date(datetime.date.today().year,datetime.date.today().month-2,1)
        if RPS == 20:
            lastMonth = datetime.date(datetime.date.today().year,datetime.date.today().month-2,1)
        elif RPS == 60:
            lastMonth = datetime.date(datetime.date.today().year,datetime.date.today().month-6,1)
        elif RPS == 120:
            lastMonth = datetime.date(datetime.date.today().year-1,datetime.date.today().month,1)
        else:
            lastMonth = datetime.date(datetime.date.today().year-2,datetime.date.today().month,1)
        lastMonthString = lastMonth.strftime('%Y-%m-%d')
        return lastMonthString
    
    @classmethod
    def stringFromconvertDateType(self,date,oldType,newType):
        temp_string=""
        if isinstance(date,str):
            temp_date = datetime.strptime(date,oldType)
            temp_string = temp_date.strftime(newType)
        else:
            temp_string = date.strftime(newType)
        return temp_string


    
    
    #将数组分割成8个数组 并行操作
    @classmethod
    def list_split(self,items,n):
        return [items[i:i+n] for i in range(0, len(items), n)]

  #shutil.copyfile应用,参数必须具体到文件名
    @classmethod
    def mycopyfile(self,srcfile,dstfile):
        if not os.path.isfile(srcfile):
            print(("%s not exit!" % (srcfile)))
        else:
            fpath,fname=os.path.split(dstfile)

            if not os.path.exists(fpath):
                os.makedirs(fpath)
                shutil.copyfile(srcfile,dstfile)
            else:
                shutil.copyfile(srcfile,dstfile)
                
    @classmethod
    #根据字符串中的数字排序
    def sort_key(self,s):
        # 排序关键字匹配
    # 匹配开头数字序号
        if s:
            try:
                kk = re.compile(r'\d+')
                c = re.findall(kk, s)[0]
            except:
                c = -1
            return int(c)
        
        
    @classmethod
    def getLocalColor(self,index):
        localcolors = [
            '#FF6384',
            '#FF9F40',
            '#FFCD56',
            '#4BC0C0',
            '#36A2EB',
            '#9966FF',
            '#C9CBCF',
            '#D15B71',
            '#1DC2DC',
            '#F08080']
        return localcolors[index]
    
    
    @classmethod
    def getBrightColor(self):
        # 获得亮色，保证其中两色分别90和ff，第三色为任意值即可
        full_range = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
        combination = ["40"]
        # 将 ff 随机插入 90 前或后
        combination.insert(random.randint(0,1),"ff")
        third_color = "{0}{1}".format(full_range[random.randint(0,15)],full_range[random.randint(0,15)])
        combination.insert(random.randint(0,2),third_color)
        color = "#" + "".join(combination)
        return self.getLocalColor(random.randint(0,9))
    
    #接受参数为 20220118 格式的时间字符串
    @classmethod
    def  getBeforeDay(self,the_day,days_count=365): 
            the_year_day=datetime.strptime(the_day, '%Y%m%d')-timedelta(days=days_count)
            the_year_day_str=datetime.strftime(the_year_day, '%Y%m%d')  
            return the_year_day_str
                
                
    #数组嵌套字典，根据value值，拆分数据       
    @classmethod
    def getArrayFormDicKeyValue(self,values,key):
        res = []
        ips = set([ values[i][key] for i in range(0,len(values))])
        for ip in ips:
            tmp = []
            for i in range(0,len(values)):
                #获取相同的IP所在的字典
                if ip == values[i][key]:
                    tmp.append(values[i]) #追加列表
            res.append(tmp)
        return res
    
    #字典根据value值分组      
    @classmethod
    def remakeStocksGroupByBK(self,values,key):
        if values == None or len(values) <=0:
            return {}
        #根据板块分组
        d1 = {}
        for i in values:                
            if i[key] not in d1:
                d1[i[key]] = [i]
            else:
                d1[i[key]].append(i)
        return d1
    
    @classmethod
    def jsonString(self,values):
        return json.dumps(values,ensure_ascii=False,indent=2 )
    
    
   
    @classmethod
    def sendMail(self,data):

        sender = '17610093388@163.com'
        receivers = ['17610093388@163.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
        
        mail_host="smtp.163.com"  #设置服务器
        mail_user="17610093388@163.com"    #用户名
        mail_pass="qaz114322"   #口令 

        message = MIMEText(data, 'html', 'utf-8')
        message['From'] = Header("股票服务器", 'utf-8')   # 发送者
        message['To'] =  Header("Yang", 'utf-8')        # 接收者
        message['Subject'] = Header("股票数据更新完成", 'utf-8')
        
        
        try:
            smtpObj = smtplib.SMTP() 
            smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
            smtpObj.login(mail_user,mail_pass)  
            smtpObj.sendmail(sender, receivers, message.as_string())
            print("邮件发送成功")
        except smtplib.SMTPException:
            print( "Error: 无法发送邮件 %s" %(smtplib.SMTPException))
            
            
    @classmethod   
    def listToDic(self,data): #元组列表转字典，[(a,1),(b,2)] -> {a:1,b:2}
        aa=sorted(data.items(), key=lambda x: x[1],reverse=True)
        bb_key = [item[0] for item in aa if item[1]>=0]
        bb_value = [item[1] for item in aa if item[1]>=0]
        bb = dict(zip(bb_key, bb_value)) 
        return bb
    
    @classmethod   
    def isLimitUpOrDown(self,ts_code,close,last_close,percent): #是否涨停或者跌停
        mark_pect = 0.1
        if ts_code.startswith("300") or ts_code.startswith("688"):
            mark_pect = 0.2 #
        if ts_code.startswith("*S"):
            mark_pect = 0.05 #
        if ts_code.endswith("BJ"):
            mark_pect = 0.3 #
        if close >= last_close:
            #涨
            limit_close = RD(last_close*(1+mark_pect),2) #四舍五入保留两位小数
            limit_close_price = RD(last_close*mark_pect,2) #四舍五入保留两位小数
            limit_percent= RD(float(limit_close_price/last_close)*100,2)
            if close == limit_close or percent == limit_percent:
                return 1
            else:
                return 0
        else:
            #跌
            limit_close = RD(last_close*(1-mark_pect),2) #四舍五入保留两位小数
            limit_close_price = RD(last_close*mark_pect,2) #四舍五入保留两位小数
            limit_percent= RD(float(limit_close_price/last_close)*100,2)

            if close == limit_close or ABS(percent) == ABS(limit_percent):
                return -1
            else:
                return 0
    @classmethod  
    def isDecrease(self,a,n):
        
        if n == 0 or len(a) <=1:
            return True
        if n == 1 and a[1]<=a[0]:
            return True

        return (a[n-1] <= a[n-2]) and self.isDecrease(a,n-1)
            
            
    @classmethod    
    def getNonRepeatList(self,data):
        new_data = []
        for i in range(len(data)):
            if data[i] not in new_data:
                new_data.append(data[i])
        return new_data
